﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LibrarySync2.Common.Extensions;
using LibrarySync2.Common.Interfaces;
using LibrarySync2.Metadata;

namespace LibrarySync2.Business.FileSystem.Item
{
    public class FileSystemItemFactory
    {
        public Library CreateLibrary(string libraryPath)
        {
            if (string.IsNullOrEmpty(libraryPath))
                throw new ArgumentNullException("libraryPath");

            if (!libraryPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                libraryPath = string.Concat(libraryPath, Path.DirectorySeparatorChar.ToString());

            var rootDirectory = new DirectoryInfo(libraryPath);
            if (!rootDirectory.Exists)
                throw new ArgumentException(string.Format("Specified path '{0}' does not exist.", libraryPath));

            return new Library(rootDirectory);
        }

        internal IFileSystemItem CreateFileSystemItem(FileSystemInfo info, string root)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            if (string.IsNullOrEmpty(root))
                throw new ArgumentNullException("root");

            var file = info as FileInfo;
            if (file != null)
                return CreateFileSystemItem(file, root);

            var directory = info as DirectoryInfo;
            if (directory != null)
                return CreateFileSystemItem(directory, root);

            throw new ApplicationException("Unexpected type of FileSystemInfo subtype: " + info.GetType());
        }

        internal IFileSystemItem CreateFileSystemItem(FileInfo file, string root)
        {
            if (file == null)
                throw new ArgumentNullException("file");
            if (string.IsNullOrEmpty(root))
                throw new ArgumentNullException("root");

            return (file.IsMediaFile()) ?
                new MediaFile(file, root, new TMDbMetadataProvider()) :
                new File(file, root);
        }

        internal IFileSystemItem CreateFileSystemItem(DirectoryInfo directory, string root)
        {
            if (directory == null)
                throw new ArgumentNullException("directory");
            if (string.IsNullOrEmpty(root))
                throw new ArgumentNullException("root");

            return new Directory(directory, root);
        }
    }
}
